package com.crm.api.controller;

import com.crm.api.common.Result;
import com.crm.api.entity.BusinessType;
import com.crm.api.service.BusinessTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 业务类型控制器
 */
@Slf4j
@RestController
@RequestMapping("/business-types")
public class BusinessTypeController {

    @Autowired
    private BusinessTypeService businessTypeService;

    /**
     * 获取业务类型列表
     */
    @GetMapping
    public Result<Map<String, Object>> getBusinessTypes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String typeName,
            @RequestParam(required = false) Boolean isActive) {
        
        log.info("获取业务类型列表: page={}, size={}, typeName={}, isActive={}", 
                page, size, typeName, isActive);
        
        Map<String, Object> result = businessTypeService.getBusinessTypes(page, size, typeName, isActive);
        return Result.success(result);
    }

    /**
     * 获取所有启用的业务类型（不分页，用于下拉选择）
     */
    @GetMapping("/active")
    public Result<List<BusinessType>> getActiveBusinessTypes() {
        log.info("获取所有启用的业务类型");
        
        List<BusinessType> businessTypes = businessTypeService.getActiveBusinessTypes();
        return Result.success(businessTypes);
    }

    /**
     * 获取业务类型详情
     */
    @GetMapping("/{id}")
    public Result<BusinessType> getBusinessType(@PathVariable Integer id) {
        log.info("获取业务类型详情: id={}", id);
        
        BusinessType businessType = businessTypeService.getBusinessTypeById(id);
        if (businessType == null) {
            return Result.error(404, "业务类型不存在");
        }
        
        return Result.success(businessType);
    }

    /**
     * 创建业务类型
     */
    @PostMapping
    public Result<BusinessType> createBusinessType(@Valid @RequestBody BusinessType businessType) {
        log.info("创建业务类型: typeName={}", businessType.getTypeName());
        
        // 检查类型名称是否已存在
        if (businessTypeService.existsByTypeName(businessType.getTypeName())) {
            return Result.error(400, "业务类型名称已存在");
        }
        
        BusinessType createdBusinessType = businessTypeService.createBusinessType(businessType);
        return Result.success(createdBusinessType);
    }

    /**
     * 更新业务类型
     */
    @PutMapping("/{id}")
    public Result<BusinessType> updateBusinessType(@PathVariable Integer id, @Valid @RequestBody BusinessType businessType) {
        log.info("更新业务类型: id={}, typeName={}", id, businessType.getTypeName());
        
        businessType.setId(id);
        
        // 检查类型名称是否已被其他记录使用
        if (businessTypeService.existsByTypeNameAndNotId(businessType.getTypeName(), id)) {
            return Result.error(400, "业务类型名称已存在");
        }
        
        BusinessType updatedBusinessType = businessTypeService.updateBusinessType(businessType);
        if (updatedBusinessType == null) {
            return Result.error(404, "业务类型不存在");
        }
        
        return Result.success(updatedBusinessType);
    }

    /**
     * 删除业务类型
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteBusinessType(@PathVariable Integer id) {
        log.info("删除业务类型: id={}", id);
        
        // 检查是否有关联的业务
        if (businessTypeService.hasRelatedBusinesses(id)) {
            return Result.error(400, "该业务类型下还有关联的业务，无法删除");
        }
        
        boolean deleted = businessTypeService.deleteBusinessType(id);
        if (!deleted) {
            return Result.error(404, "业务类型不存在");
        }
        
        return Result.success();
    }

    /**
     * 启用/禁用业务类型
     */
    @PatchMapping("/{id}/status")
    public Result<Void> toggleBusinessTypeStatus(@PathVariable Integer id, @RequestBody Map<String, Boolean> request) {
        Boolean isActive = request.get("isActive");
        log.info("切换业务类型状态: id={}, isActive={}", id, isActive);
        
        boolean updated = businessTypeService.updateBusinessTypeStatus(id, isActive);
        if (!updated) {
            return Result.error(404, "业务类型不存在");
        }
        
        return Result.success();
    }
}